#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <cassert>
#include <unistd.h>
#include <string>
#include <cstring>

#define PATH "./"
#define PROJID 0x333
#define SIZE 4096

class Shm{
private:
    key_t key;
    int shmid;
    mode_t mode = 0666;
public:
    Shm(){
        key = getKey();
    }
    key_t getKey()
    {
        /**
         * function：返回并设置key值
         * return: 返回key值
         * @return 
         */
        key_t k = ftok(PATH,PROJID);
        assert(k!=-1);
        return key = k;
    }
    int createShm()
    {
        /**
         * function:创建共享内存
         * return：返回共享内存的标识符
         * @return
         */
        int sid = shmget(key,SIZE,IPC_CREAT|IPC_EXCL|mode);
        assert(sid!=-1);
        return shmid = sid;
    }
    int getShm()
    {
        /**
         * function:获取共享内存
         * return: 返回共享内存的标识符
         * @return
         */
        int sid = shmget(key,SIZE,IPC_CREAT);
        assert(sid!=-1);
        return shmid = sid;
    }
    char* processAssociation()
    {
        /**
         * function:进行进程于共享内存间的关联
         * return:返回共享内存的是起始地址
         * @return
         */
        char* start = (char*)shmat(shmid,nullptr,0);
        assert((void*)start!=(void*)-1);
        return start;
    }
    void deAssociation(void* start)
    {
        /**
         * function:进行去关联
         * :parame start 共享内存的起始地址
         */
        shmdt(start);
    }
    void release()
    {
        /**
         * function:释放共享内存
         */
        int n = shmctl(shmid,IPC_RMID,nullptr);
        assert(n!=-1);
    }
    int getShmid()
    {
        /**
         * @return 
         */
        return shmid;
    }
};